#include "reg52.h"
#include "ds1302.h"

code unsigned char Seg_Table[] = 
{
0xc0, //0
0xf9, //1
0xa4, //2
0xb0, //3
0x99, //4
0x92, //5
0x82, //6
0xf8, //7
0x80, //8
0x90, //9
0x88, //A
0x83, //b
0xc6, //C
0xa1, //d
0x86, //E
0x8e, //F
0xbf,//-	
};

unsigned char code Read_Addr[7] = {0x81,0x83,0x85,0x87,0x89,0x8b,0x8d};
unsigned char code Write_Addr[7] = {0x80,0x82,0x84,0x86,0x88,0x8a,0x8c};
unsigned char Time[7] = {0x12,0x58,0x14,0x04,0x04,0x04,0x24};

void InitHC573(unsigned char channel)
{
	switch(channel)
	{
		case 4:
			P2 = (P2 & 0x1f) | 0x80;
			break;
		case 5:
			P2 = (P2 & 0x1f) | 0xa0;
			break;
		case 6:
			P2 = (P2 & 0x1f) | 0xc0;
			break;
		case 7:
			P2 = (P2 & 0x1f) | 0xe0;
			break;
		case 0:
			P2 = (P2 & 0x1f) | 0x00;
			break;
	}

}
void WriteTime()
{
	char i = 0;
	Write_Ds1302_Byte(0x8e,0x00);
	for( i = 0;i<7;i++)
	{
		Write_Ds1302_Byte(Write_Addr[i],Time[i]);
	}
	Write_Ds1302_Byte(0x8e,0x80);
}

void ReadTime()
{
	char i = 0;
		for(i = 0;i<7;i++)
	{
		Time[i] = Read_Ds1302_Byte(Read_Addr[i]);
	}
}

void SMG_Bit(unsigned pos,unsigned char dat)
{
	InitHC573(6);
	P0 = 0x01<<pos;
	InitHC573(7);
	P0 = dat;
  InitHC573(0);

}

void Delay(unsigned int t)
{
	while(t--);
}

void InitSMG()
{
	InitHC573(6);
	P0 = 0xff;
	InitHC573(7);
	P0 = 0xff;
  InitHC573(0);
		Delay(100);
}



void ShowSMG()
{
	SMG_Bit(7,Seg_Table[Time[0]%16]);
	Delay(100);
	SMG_Bit(6,Seg_Table[Time[0]/16]);
	Delay(100);
	
	SMG_Bit(5,Seg_Table[16]);
	Delay(100);
	
	SMG_Bit(4,Seg_Table[Time[1]%16]);
	Delay(100);
	SMG_Bit(3,Seg_Table[Time[1]/16]);
	Delay(100);
	
	SMG_Bit(2,Seg_Table[16]);
	Delay(100);
	
	SMG_Bit(1,Seg_Table[(Time[2]%16)]);
	Delay(100);
	SMG_Bit(0,Seg_Table[(Time[2]/16)]);
	Delay(100);
	
	InitSMG();
}

int main()
{
	 WriteTime();

	while(1)
	{
		 ReadTime();
		ShowSMG();
		
	}
}